package com.dushiguang.findhoney;


import android.Manifest;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.dushiguang.findhoney.API.FindHoneyAPI;
import com.dushiguang.findhoney.BaiduMap.MyBaiduMap;
import com.dushiguang.findhoney.Bean.InfoDetails;
import com.dushiguang.findhoney.Bean.LiveBean;
import com.dushiguang.findhoney.BmobDB.BmobMethod;
import com.dushiguang.findhoney.Fragment.ViewPagerFragment;
import com.dushiguang.findhoney.Fragment.ViewPagerFragment_;
import com.dushiguang.findhoney.Utils.DataStorage.Db.DbUtil;
import com.dushiguang.findhoney.Utils.DataStorage.SharedPreferences.SharedPreferenceService;
import com.dushiguang.findhoney.View.CircleMenu.CircleMenuLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.List;

@EActivity(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    private LocationManager mLocationManager;
    private BmobMethod mBmobMethod;
    private String mLocationProvider;
    private FindHoneyAPI api;
    private FragmentManager mFragmentManager;
    //Banner要展示的图片
    private int mLocalPic[] = {R.mipmap.email, R.mipmap.facebook, R.mipmap.google, R.mipmap.linkedin, R.mipmap.pinterest};

    String ret = null;
    DbUtil initDb;

    //private CircleMenuLayout mCircleMenuLayout;
    private String[] mItemTexts = new String[]{"地图 ", "手电筒", "信息",
            "打电话", "设置", "共享位置"};
    private int[] mItemImgs = new int[]{R.mipmap.maps,
            R.mipmap.flashlight, R.mipmap.mms,
            R.mipmap.phone, R.mipmap.settings,
            R.mipmap.updater};

    @ViewById(R.id.id_menulayout)
    CircleMenuLayout mCircleMenuLayout;

    @Extra("ObjectId")
    String ObjectId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("dushiguang", "MainActivity == onCreate()");
        mFragmentManager = getSupportFragmentManager();
    }

    /**
     * 获取用户的位置
     */
    private void InitLocation() {
        boolean goNext = true;
        //获取地理位置管理器
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = mLocationManager.getProviders(true);

        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            mLocationProvider = LocationManager.GPS_PROVIDER;
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Location location = mLocationManager.getLastKnownLocation(mLocationProvider);
            if (location != null) {
                showLocation(location);
                goNext = false;
            }
        }

        if (providers.contains(LocationManager.NETWORK_PROVIDER) && goNext) {
            mLocationProvider = LocationManager.NETWORK_PROVIDER;
            Location location = mLocationManager.getLastKnownLocation(mLocationProvider);
            if (location != null) {
                showLocation(location);
            }
        } /*else {
            Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return ;
        }*/
        Location location = mLocationManager.getLastKnownLocation(mLocationProvider);
    }

    /**
     * 显示地理位置经度和纬度信息
     *
     * @param location
     */
    private void showLocation(Location location) {
        if (location != null) {
            String locationStr = "纬度：" + location.getLatitude() + "\n" + "经度：" + location.getLongitude();
            Log.e("dushiguang", "经纬度=====" + locationStr);
            Toast.makeText(this, locationStr, Toast.LENGTH_SHORT).show();
            //将将经纬度存储
            mBmobMethod = new BmobMethod();
            mBmobMethod.initBmob(this);
            //TODO DELETE THIS
            ObjectId = "1e28fd67f1";
            mBmobMethod.UpdateBmobDb(this, location, ObjectId);
        }
    }

    @AfterViews
    void afterViews() {
        api = new FindHoneyAPI();
        mCircleMenuLayout.setMenuItemIconsAndTexts(mItemImgs, mItemTexts);

        mCircleMenuLayout.setOnMenuItemClickListener(new CircleMenuLayout.OnMenuItemClickListener() {

            @Override
            public void itemClick(View view, int pos) {
                Toast.makeText(MainActivity.this, mItemTexts[pos], Toast.LENGTH_SHORT).show();
                switch (pos) {
                    case 0:
                        MyBaiduMap.jumpToBaiduMap(MainActivity.this);
                        break;
                    case 1:
                        GuideActivity.jumpToGuideActivity(MainActivity.this);
                        break;
                    case 2:
                        getData();
                        break;
                    case 3:
                        getCatchData();
                        break;
                    case 4:
                        Intent intent = new Intent(MainActivity.this, MainTestActivity.class);
                        startActivity(intent);
                        break;
                    case 5:
                        InitLocation();
                        break;

                }
            }

            @Override
            public void itemCenterClick(View view) {
                Toast.makeText(MainActivity.this, "you can do something", Toast.LENGTH_SHORT).show();
                SharedPreferenceService sp = new SharedPreferenceService(getApplication());

                sp.putStringValue("key1", "this is the fast Data");

                String str = sp.getStringValue("key1");
                Log.e("dushiguang", "SharedPreferenceService---->>" + str);

            }

        });

        showBanner();
    }

    @Background()
    void getData() {
        //获取API数据使用fastjson解析成Bean
        LiveBean liveBean = api.getLiveBean();

        if (null != liveBean) {
            int size = liveBean.getData().size();
            int i, j;

            //TODO 使用增强for循环(foreach循环)
            for (i = 0; i < size; i++) {
                InfoDetails minfoDetails = liveBean.getData().get(i);
                Log.e("dushiguang", "Area======>>" + minfoDetails.getArea());
                int actSize = minfoDetails.getAct().size();
                String actStr = null;
                for (j = 0; j < actSize; j++) {
                    actStr = minfoDetails.getAct().get(j);
                    Log.e("dushiguang", "act======>>" + actStr);
                }
            }
        }
    }

    public void getCatchData() {
        initDb = new DbUtil(getApplication());
        //initDb.updateCacheData("1", "this is fast login in");
        String ret = initDb.getCatchData("1");
        Log.e("dushiguang", "getCatchData-------->>>>" + ret);
    }

    /**
     * 展示Banner
     */
    public void showBanner() {

        if (isFinishing()) {
            return;
        }

        FragmentTransaction ft = mFragmentManager.beginTransaction();
        ViewPagerFragment_ vpf = new ViewPagerFragment_();
        // 如果图片是从网上获取,使用setImgUrls来设置图片加载路径
        //vpf.setImgUrls(null);//显示五张图片
        //如果使用App内的图片使用setImgIds设置图片
        vpf.setImgIds(mLocalPic);
        vpf.setIsAutoSwitch(false);//是否字典切换
        vpf.setOnImgItemClickListener(new ViewPagerFragment.OnImgItemClickListener() {
            @Override
            public void onItemClick(int position, String imgUrl) {
                //TODO 点击图片后跳入相应的界面
                Log.e("dushiguang","position=====>>" + position + "被点击" + "==imgUrl==" + imgUrl);
            }
        });
        ft.replace(R.id.banner_fl_fl, vpf);
        ft.commitAllowingStateLoss();
    }
}
